import 'package:get/get.dart';
import 'package:xuance/RoutePath.dart';
import 'package:xuance/bean/LoginHistoryBean.dart';
import 'package:xuance/network/api/UserApi.dart';
import 'package:xuance/page/main/me/me_state.dart';
import 'package:xuance/util/cache_util.dart';
import 'package:xuance/util/toast_util.dart';
import 'package:xuance/widget/dialog/CommonCenterDialog.dart';

class MeLogic extends GetxController {
  MeState state = MeState();
  var username = "".obs;
  var page = 1.obs;
  @override
  void onInit() {
    super.onInit();
    init();
  }

  Future<void> init() async {
    var user = await CacheUtil.getUser();
    username.value = user?.userName ?? "";
    try {
      LoginHistoryBean? res =
          await UserApi.loginHistory(user?.userCode, page.value);
      state.totalPage.value = res?.pageNum?.toInt() ?? 0;
      state.list.clear();
      state.list.addAll(res?.list ?? []);
    } catch (e) {
      print(e);
    }
  }

  void logout() {
    showCommonCenterDialog("是否退出登录？", onConfirm: () async {
      await CacheUtil.setToken(null);
      await CacheUtil.setUser(null);
      Get.offAllNamed(RoutePath.login);
    });
  }

  void lastPage() {
    if (page.value <= 1) {
      page.value = 1;
      showToast("已经是最后一页");
    } else {
      page.value--;
      init();
    }
  }

  void nextPage() {
    if (page.value >= state.totalPage.value) {
      page.value = state.totalPage.value;
      showToast("已经是第一页");
    } else {
      page.value++;
      init();
    }
  }
}
